/**
 * Test TypeScript Server Readiness Caching Optimization
 * 
 * This test verifies that:
 * 1. First call waits for TypeScript server (5000ms delay)
 * 2. Subsequent calls skip the delay when server is ready (cached flag)
 * 3. Context is properly updated with readiness flag
 */

const vscode = require('vscode');
const path = require('path');

// Mock VS Code Extension Context
class MockExtensionContext {
  constructor() {
    this.globalState = new Map();
  }
  
  get globalState() {
    return {
      get: (key, defaultValue) => {
        return this._globalState.get(key) ?? defaultValue;
      },
      update: async (key, value) => {
        this._globalState.set(key, value);
        console.log(`Context updated: ${key} = ${value}`);
        return Promise.resolve();
      }
    };
  }
  
  set globalState(value) {
    this._globalState = value;
  }
}

async function testTSServerCaching() {
  console.log('=== TypeScript Server Caching Test ===');
  
  // Create mock context
  const context = new MockExtensionContext();
  
  // Mock VS Code document
  const mockDocument = {
    uri: { fsPath: path.join(__dirname, 'store', 'index.ts') },
    languageId: 'typescript'
  };
  
  // Mock VS Code workspace
  const originalWorkspace = vscode?.workspace;
  if (vscode) {
    vscode.workspace = {
      ...originalWorkspace,
      openTextDocument: async () => mockDocument
    };
    
    // Mock VS Code commands for symbol provider
    vscode.commands = {
      executeCommand: async (command, uri) => {
        console.log(`Executing command: ${command} for ${uri.fsPath}`);
        // Simulate TypeScript server returning symbols
        return [
          {
            name: 'default',
            kind: 13, // Variable kind
            children: [
              {
                name: 'actions',
                kind: 7, // Property kind
                children: [
                  { name: 'testAction1', kind: 6 }, // Method kind
                  { name: 'testAction2', kind: 7 }  // Property kind
                ]
              }
            ]
          }
        ];
      }
    };
  }
  
  try {
    // Import after mocking
    const { VSCodeASTParser } = require('../src/utils/vscodeAstParser');
    
    console.log('Testing first call (should have delay)...');
    const start1 = Date.now();
    
    const result1 = await VSCodeASTParser.getModuleActionNamesWithVSCode(
      mockDocument.uri.fsPath,
      'testModule',
      ['setData', 'setConfig'],
      context
    );
    
    const duration1 = Date.now() - start1;
    console.log(`First call completed in ${duration1}ms`);
    console.log('First call results:', result1);
    
    // Verify cache flag is set
    const isServerReady = context.globalState.get('xlogicTips.tsServerReady', false);
    console.log('Server ready flag after first call:', isServerReady);
    
    console.log('\nTesting second call (should skip delay)...');
    const start2 = Date.now();
    
    const result2 = await VSCodeASTParser.getModuleActionNamesWithVSCode(
      mockDocument.uri.fsPath,
      'testModule',
      ['setData', 'setConfig'],
      context
    );
    
    const duration2 = Date.now() - start2;
    console.log(`Second call completed in ${duration2}ms`);
    console.log('Second call results:', result2);
    
    // Verify optimization worked
    console.log('\n=== Test Results ===');
    console.log(`First call duration: ${duration1}ms (should be ~5000ms+)`);
    console.log(`Second call duration: ${duration2}ms (should be <1000ms)`);
    console.log(`Speed improvement: ${(duration1 / duration2).toFixed(2)}x faster`);
    
    const isOptimized = duration2 < 1000 && duration1 > 4000;
    console.log(`Optimization working: ${isOptimized ? 'YES ✅' : 'NO ❌'}`);
    
    if (isOptimized) {
      console.log('✅ TypeScript server caching optimization is working correctly!');
    } else {
      console.log('❌ Optimization may not be working as expected');
    }
    
  } catch (error) {
    console.error('Test error:', error);
  }
}

// Run test if this file is executed directly
if (require.main === module) {
  testTSServerCaching().catch(console.error);
}

module.exports = { testTSServerCaching };